//同步代码块
package daily.may0531;

public class SafeSellTicketBySynchronizedTest {
    public static void main(String[] args) {
        //匿名内部类
        Runnable tw = new Runnable() {
            //定义一个多个线程共享的票源
            private int tickets = 10000;
            //创建一个任意的对象，作为锁对象
            Object lock = new Object();
            //设置线程任务:卖票
            @Override
            public void run() {
                //使用死循环,让卖票操作重复执行
                while(true){
                    //同步代码块
                    synchronized (lock){
                        if (tickets > 0) {
                            //假设卖一张票要线程休眠10毫秒
                            try {
                                Thread.sleep(10);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            System.out.printf("%s窗口第%d张票已经售出\n", Thread.currentThread().getName(), tickets--);
                        }
                    }
                }
            }
        };
        //4个窗口一起卖票
        new Thread(tw, "窗口1").start();
        new Thread(tw, "窗口2").start();
        new Thread(tw, "窗口3").start();
        new Thread(tw, "窗口4").start();
    }
}
